<?php

class TipoPermissaoModel extends AppModel {

	protected $_tableName = "tipo_permissao";
	
	public static function findNomePermissaoById($id) {
		if( $id == 0 )
			return "Administrador";
		$tipoPermissao = new TipoPermissaoModel();
		$response = $tipoPermissao->findById($id);
		return $response['nome'];
	}
	
	public static function createHeadersToTable() {
		$headers = array( 
					array( "th" => "Nome" ),
					array( "th" => "Status" ),
					array( "th" => "Áreas do Sistema" ),
					array( "th" => "Ações")
				);
		return $headers;
	}
	
	public static function listAllToTable($controllers=array(), $separator="/") {
		$response = array();
		
		$tipoPermissaoModel = new TipoPermissaoModel();
		$tiposPermissoes = $tipoPermissaoModel->findAll();
		
		foreach ( $tiposPermissoes as $tipoPermissao ){
		
			$lineResponse = array();
			$lineResponse['id'] = Encryption::encode( $tipoPermissao['id'] );
			$lineResponse['nome'] = $tipoPermissao['nome'];
			$lineResponse['status'] = Status::convertToString( $tipoPermissao['ativo'] );
			$permissaoModel = new PermissaoModel();
			$permissoes = $permissaoModel->find(array("tipo_permissao_id" => $tipoPermissao['id']));
			$lineResponse['menus'] = "Início";
			foreach ($permissoes as $permissao){
				$lineResponse['menus'] .= " ".$separator." ".$controllers[ $permissao['controller'] ];
				$tmpActions = explode("-", $permissao['actions']);
				$class = PermissaoController::getReflectionClass( $permissao['controller'] );
				if( $class->implementsInterface('ItemMenu') ){
					$arr = PermissaoController::getActionsArrayItemMenu($class);
					$lineResponse['menus'] .= ( count( $tmpActions ) == (count( $arr )+1) ) ? "(Acesso Total)" : "(Acesso Parcial)";
				}else if( PermissaoController::inBasicSystem($permissao['controller']) ){
					$lineResponse['menus'] .= "(Acesso Permitido)";
				}else{
					$arr = PermissaoController::getActionsArrayNotItemMenu($class);
					$lineResponse['menus'] .= ( count( $tmpActions ) == count( $arr ) ) ? "(Acesso Total)" : "(Acesso Parcial)";
				}
			}
			$response[] = $lineResponse;
				
		}
		
		return $response;
		
	}
	
	public static function convertToSelectArray($idSelected="") {
		$tipoPermissaoModel = new TipoPermissaoModel();
		$tiposPermissoes = $tipoPermissaoModel->findAndOrderBy(array("ativo" => 1), "nome");
		$response = array();
		foreach ($tiposPermissoes as $tipoPermissao){
			$tmp = array();
			$tmp[ "option.value" ] = Encryption::encode($tipoPermissao['id']);
			if( $tipoPermissao['id'] == $idSelected )
				$tmp[ "option.selected" ] = "selected";
			$tmp[ "option.label" ] = $tipoPermissao['nome'];
			$response[] = $tmp;
		}
		return $response;
	}
	
}

?>